/** file AudioArts.cpp
    author belot.nicolas
*/

#include "AudioArts.h"
#include "nbarts.h"
#include <iostream>
#include <cassert>
namespace libtrckr {

double *AudioArts::_buffer=0;

int AudioArts::cnt=0;

int process(int nframes, void* arg){
	AudioArts *a=(AudioArts*)arg;
	if( a->getFrames(nframes,AudioArts::_buffer) > 0){
		memcpy(a->getArtsBuffer(), AudioArts::_buffer, sizeof(double)*nframes*a->channels());
		return nframes;
	}
	return 0;
}

AudioArts::AudioArts(){
	_buffer=0;
	cnt++;
}

AudioArts::AudioArts(const AudioArts& a){
	channels(a.channels());
	bitrate(a.bitrate());
	_buffer=0;
	cnt++;
}

AudioArts::~AudioArts( ){
	if(_buffer!=0){
		free(_buffer);
	}
	cnt--;
	if(cnt<=0 && sbuffer!=0){
		free(sbuffer);
		sbuffer=NULL;
	}
}

void AudioArts::open(){
	if(!*lock){
	if(_buffer==0){
		_buffer=(double*)malloc(sizeof(double)*2048);
		
	}
	if(sbuffer==0){	
		sbuffer=(double*)malloc(sizeof(double)*bitrate()*channels());
		*capacity=bitrate()*channels();
	}
	*start=0;
	*end=0;
	*size=0;
	nbarts_set_callback(process,this );
	stream = nbarts_get_stream();
	if(stream==NULL){
		_state=INVALID;
	}else{
		_state=OPEN;
	}
	*lock=true;
	}
}

Audio::audio_state_t AudioArts::state(){
	return _state;
}

double *AudioArts::getArtsBuffer(){
	return getIn();
}

void AudioArts::close(){
	nbarts_close_stream(stream);
	_state=CLOSE;
	*lock=false;
}

int AudioArts::append(Buffer b){
		if(*size+(b.size()*channels())>*capacity){
			return 0;
		}else{
			copy(b);
		}
}

void AudioArts::param(std::string name, std::string value){}

void AudioArts::param(std::string name, double value){}
void AudioArts::param(std::string name, int value){}

}
